package syncer.server;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


public class SyncServer {

	public static boolean DEBUG = true;
	private static SyncServer instance = new SyncServer(); 
	private Map<Integer,Object> syncList = new HashMap<Integer,Object>();
	
	private Map<Object,Integer> reverList = new HashMap<Object,Integer>();//reversed syncList, for retrieving the id of a given obj
	
	private SyncServer(){
		
	}
	
	public static SyncServer getInstance(){
		return instance;
	}
	
	public Object getById(int id){
		return syncList.get(id);
	}
	
	public int getIdOf(Object obj){
		return reverList.get(obj);
	}
	
	public void setObject(int id, Object obj){
		syncList.put(id, obj);
		reverList.put(obj, id);
	}
		
	public Object insertObj(Object obj){
		if(obj == null){
			if(DEBUG){
				System.out.println("null Object!");
			}
			return null;
		}
		if(syncList.containsKey(obj.hashCode())){
			if(DEBUG){
				System.out.println(obj.toString() + "exsisted!!");
			}
			return null;
		}
		setObject(obj.hashCode(), obj);
		
		Field[] fields = obj.getClass().getDeclaredFields();
		for(Field f:fields){
			f.setAccessible(true);
			if(f.getType()==null)
				continue;
			try {
				Object var = f.get(obj);
				if(DEBUG){
					System.out.println(var);
				}
				insertObj(var);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return obj;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
